import { defineStore } from 'pinia';
import router from '@/plugins/router';
import Cookies from 'js-cookie';

// TODO 测试用
declare type UserDetail = {
  email: string;
  mobile?: string;
  isManager: boolean;
};

// TODO 测试用
declare type UserInfo = {
  name: string;
  description?: string;
  userDetail: UserDetail;
};

declare type AuthUser = {
  token: string;
  // TODO 测试用
  userInfo: UserInfo;
};

export const useUserStore = defineStore('user', {
  state: (): AuthUser => ({
    token: 'test',
    // TODO 测试用
    userInfo: { name: 'test', userDetail: { email: 'email test', isManager: false } },
  }),
  actions: {
    refreshUserInfo(user: AuthUser) {
      Object.assign(this, user);
    },
    userLogin(user: AuthUser) {
      Object.assign(this, user);
      //TODO 处理动态路由
      router.push({ path: '/home' });
    },
    clearState() {
      this.token = '';
    },
    logout() {
      this.token = '';
      Cookies.remove('token');
      Cookies.remove('refreshToken');
    },
  },
  // TODO 测试用
  cnPersist: {
    states: {
      userInfo: {
        includes: { name: true, description: true, userDetail: { email: true, isManager: true } },
        policy: 'HASH',
        serialize: newValue => {
          if (!newValue) {
            return null;
          }
          return JSON.stringify(newValue);
        },
      },
    },
  },
});
